﻿using AutoMapper;
using PowerHub.MES.Common.NumberingCenter;
using PowerHub.MES.DTO.Shopfloor.DTO;
using PowerHub.MES.DTO.Shopfloor.QueryDTO;
using PowerHub.MES.EFBase;
using PowerHub.MES.Entities.Shopfloor;
using PowerHub.MES.Entities;
using PowerHub.MES.IRepository.IShopfloor;
using PowerHub.MES.IServices.IShopfloor;
using PowerHub.MES.Jwt;
using PowerHub.MES.ReturnEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PowerHub.MES.IServices.IProduction;
using PowerHub.MES.Entities.Production;
using PowerHub.MES.DTO.Production.DTO;
using PowerHub.MES.DTO.Production.QueryDTO;
using PowerHub.MES.IRepository.IProduction;
using PowerHub.MES.Entities.ProductPlanning;

namespace PowerHub.MES.Services.Production
{
    /// <summary>
    /// 生产工单接口实现层
    /// </summary>
    public class Production_WorkOrderServices : BaseServices<Production_WorkOrder>, IProduction_WorkOrderServices
    {
        private IProduction_WorkOrderRepository _iProduction_WorkOrderRepository;
        public UserServices _userServices;
        private IMapper _mapper;

        public Production_WorkOrderServices(PowerHubMesContext powerHubMesContext, IProduction_WorkOrderRepository iProduction_WorkOrderRepository, UserServices userServices, IMapper mapper) : base(powerHubMesContext)
        {
            _iProduction_WorkOrderRepository = iProduction_WorkOrderRepository;
            _userServices = userServices;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取生产工单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationPageResult<List<Production_WorkOrder>>> GetProduction_WorkOrderPageListAsync(QueryProduction_WorkOrderDTO query)
        {
            return await _iProduction_WorkOrderRepository.GetProduction_WorkOrderPageListAsync(query);
        }

        /// <summary>
        /// 添加生产工单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> CreateProduction_WorkOrderAsync(Production_WorkOrderDTO query)
        {
            Production_WorkOrder foundation = await GetEntityAsync(d => d.WorkOrderName.Equals(query.WorkOrderName) && d.IsDel == 0);
            if (foundation != null)
            {
                throw new Exception("你输入的生产工单名称已存在！");
            }

            if (string.IsNullOrEmpty(query.ProductBillId))
            {
                throw new Exception("创建失败请重新选择产品后再试试！");
            }

            //判断BOM
           var MaterialsIdCoun=  query.ProductionWorkOrderBillDetials.Where(p => p.MaterialsId == null).Count();
            if (MaterialsIdCoun > 0)
            {
                throw new Exception("BOM存在缺失请关闭后重新试试！");
            }
            //判断MeasuringUnitIdCoun
            var MeasuringUnitIdCoun = query.ProductionWorkOrderBillDetials.Where(p => p.MeasuringUnitId == null).Count();
            if (MeasuringUnitIdCoun > 0)
            {
                throw new Exception("BOM计量单位存在问题！");
            }



            //实体转换
            var Production_WorkOrder = _mapper.Map<Production_WorkOrder>(query);
            Production_WorkOrder.Id = Guid.NewGuid().ToString();
            Production_WorkOrder.WorkOrderNO = string.IsNullOrEmpty(query.WorkOrderNO) || query.WorkOrderNO.Contains(" ") ? GenerateBasicDataNO.GenerateWorkOrderNO() : query.WorkOrderNO;
            Production_WorkOrder.Creator = _userServices.UserName;
            Production_WorkOrder.Status = 0;

            //设置明细id
            foreach (var item in Production_WorkOrder.ProductionWorkOrderBillDetials)
            {
                item.Id = Guid.NewGuid().ToString();
            }


            return await _iProduction_WorkOrderRepository.CreateProduction_WorkOrderAsync(Production_WorkOrder);
        }


        /// <summary>
        /// 生成编号
        /// </summary>
        /// <param name="customCode"></param>
        /// <param name="sequenceLength"></param>
        /// <returns></returns>
        public string GetWorkOrderNO(string customCode = "56", int sequenceLength = 5)
        {
            Production_WorkOrder Production_WorkOrder = GetEntityListAsync(u => u.IsDel == 0).Result.OrderByDescending(u => u.WorkOrderNO).FirstOrDefault();

            int sequenceNumber = 0;
            if (Production_WorkOrder != null)
            {
                string JobNumber = Production_WorkOrder.WorkOrderNO.Substring(Production_WorkOrder.WorkOrderNO.Length - 5);
                sequenceNumber = Convert.ToInt32(JobNumber);
            }

            // 获取当前年份的简写（只取后两位）  
            string yearShort = DateTime.Now.Year.ToString().Substring(2, 2);
            sequenceNumber++;
            string sequence = sequenceNumber.ToString().PadLeft(sequenceLength, '0');

            return yearShort + customCode + sequence;
        }

        /// <summary>
        /// 批量删除生产工单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> DeletionProduction_WorkOrderAsync(List<string>? ids)
        {
            if (ids.Count < 1)
            {
                throw new Exception("请先选择数据！");
            }
            return await _iProduction_WorkOrderRepository.DeletionProduction_WorkOrderAsync(ids);
        }


        /// <summary>
        /// 更新生产工单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> UpdateProduction_WorkOrderAsync(Production_WorkOrderDTO query)
        {
            if (query == null)
            {
                throw new Exception("请先选择数据！");
            }

            //根据id获取生产工单信息
            Production_WorkOrder Production_WorkOrder = await GetEntityAsync(d => d.Id.Equals(query.Id));
            if (Production_WorkOrder == null)
            {
                throw new Exception("更新生产工单信息发生了异常,请刷新页面后试试");
            }
            Production_WorkOrder.WorkOrderName = query.WorkOrderName;
            Production_WorkOrder.Updator = _userServices.UserName;


            return await _iProduction_WorkOrderRepository.UpdateProduction_WorkOrderAsync(Production_WorkOrder);

        }

        /// <summary>
        /// 根据生产工单id获取工单信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<Production_WorkOrder>> GetProduction_WorkOrderByIdAsync(QueryProduction_WorkOrderDTO pageQuery)
        {
            return await _iProduction_WorkOrderRepository.GetProduction_WorkOrderByIdProductionTaskListAsync(pageQuery);
        }

        /// <summary>
        /// 根据生产工单id获取分解生产任务
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<OperationResult<Production_WorkOrderProductionTaskDTO>> GetProduction_WorkOrderByIdTaskListAsync(QueryProduction_WorkOrderDTO pageQuery)
        {
            var result = new OperationResult<Production_WorkOrderProductionTaskDTO>();
            var workOrder =  await _iProduction_WorkOrderRepository.GetProduction_WorkOrderByIdProductionTaskListAsync(pageQuery);

            var workOrderProductionTaskDTO = new Production_WorkOrderProductionTaskDTO();
            workOrderProductionTaskDTO.Id = workOrder.Id;
            workOrderProductionTaskDTO.WorkOrderNO = workOrder.WorkOrderNO;
            workOrderProductionTaskDTO.WorkOrderName = workOrder.WorkOrderName;
            //工单明细
            var workOrderBillDetials=  workOrder.ProductionWorkOrderBillDetials;

            //// 每组的元素数量
            //int groupSize = 4;

            //List<List<Production_WorkOrderTask>> workOrderTasks = new List<List<Production_WorkOrderTask>>();
            //for ( var i = 0; i< workOrderBillDetials.Count; i += groupSize)
            //{
            //    var materials = workOrderBillDetials.Select(g=>new Production_WorkOrderTask(g.Materials.Id, g.Materials.MaterialsName, g.PredictQuantity)).Skip(i).Take(groupSize).ToList();
            //    workOrderTasks.Add(materials);
            //}
            workOrderProductionTaskDTO.production_WorkOrderTasks = workOrderBillDetials.Select(g => new Production_WorkOrderTask(g.Materials.Id, g.Id, g.Materials.MaterialsName, g.PredictQuantity, g.AllocatedQuantity)).ToList();
            workOrderProductionTaskDTO.OrderQuantity = workOrderBillDetials.Select(g => g.PredictQuantity).Sum();

            result.Data = workOrderProductionTaskDTO;
            return result;
        }
    }
}
